package handler

import (
	"bytes"
	"encoding/json"
	"fmt"
	"github.com/golang/protobuf/proto"
	"github.com/golang/protobuf/ptypes/wrappers"
	"github.com/valyala/fasthttp"
	"io/ioutil"
	"net/http"
)

type ChuangKuRequest struct {
	Uid       string `json:"uid"`
	Token     string `json:"token"`
	ChannelId string `json:"channelId"`
	GameID    string `json:"gameId"`
}

// 创酷登陆
func ChuangKu(ctx *fasthttp.RequestCtx) {

	//if string(ctx.Request.Header.ContentType()) != "application/json" {
	//	ctx.SetStatusCode(http.StatusBadRequest)
	//	return
	//}

	var mess wrappers.BytesValue

	if err := proto.Unmarshal(ctx.PostBody(), &mess); err != nil {
		ctx.Error(err.Error(), http.StatusBadRequest)
		return
	}

	var req ChuangKuRequest

	if err := json.Unmarshal(mess.Value, &req); err != nil {
		ctx.Error(err.Error(), http.StatusBadRequest)
		return
	}

	if resp, err := http.Post("http://ol.gzqudi.cn/qd/online/game/loginValidate", "application/json;charset=utf-8", bytes.NewBuffer(mess.Value)); err != nil {

		ctx.Error("chuangku server not connected", http.StatusInternalServerError)
		return
	} else {

		defer resp.Body.Close()
		body, _ := ioutil.ReadAll(resp.Body)

		var res = struct {
			Code int    `json:"resultCode"`
			Err  string `json:"errMsg"`
		}{}

		_ = json.Unmarshal(body, &res)
		if res.Code != 1 {
			ctx.Error(fmt.Sprintf("Code = %d: %s", res.Code, res.Err), http.StatusInternalServerError)
			return
		}
	}

	login(ctx, "chuangku-"+req.Uid)
}

//type serversService struct {
//}
//
//func (serversService) Servers(ctx context.Context, in *empty.EmptyRequest) (*pb.ServersReply, error) {
//
//	md, ok := metadata.FromIncomingContext(ctx)
//	if !ok {
//		return nil, errors.New("令牌错误")
//	}
//
//	var tokens = md["token"]
//	if len(tokens) == 0 {
//		return nil, errors.New("令牌错误")
//	}
//
//	token := tokens[0]
//
//	_, err := models.GetUserIDFromToken(token)
//	if err != nil {
//		return nil, err
//	}
//
//	servers, err := models.FindAllServers()
//	if err != nil {
//		return nil, err
//	}
//
//	serversReply := make([]*pb.Server, 0)
//	for _, v := range servers {
//
//		serversReply = append(serversReply, &pb.Server{
//			ID:      v.ID,
//			Name:    v.Name,
//			Address: v.Address,
//		})
//	}
//
//	return &pb.ServersReply{
//		Servers: serversReply,
//	}, nil
//}
